package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;


@Slf4j
@Service
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 查询行为实体数据
     * @param userId  用户id
     * @param equipmentId  设备id
     * @return
     */
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        //检验参数
        //判断userid是否为空,不为空使用userid查询,为空根据userid创建行为实体数据
        if (userId!=null){
            Query query = Query.query(Criteria.where("refId").is(userId)
            .and("type").is(ApBehaviorEntry.Type.USER.getCode()));
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            //判断该用户是否存在,不存在创建
            if (behaviorEntry==null){
                //不存在,创建
                behaviorEntry = new ApBehaviorEntry();
                behaviorEntry.setCreatedTime(new Date());
                behaviorEntry.setRefId(userId);
                behaviorEntry.setType(ApBehaviorEntry.Type.USER.getCode());
                //存入文档
                mongoTemplate.save(behaviorEntry);
            }
            return behaviorEntry;
        }
        //判断equipmentId是否为空,不为空使用equipmentId查询,为空根据equipmentId创建行为实体数据
        if (equipmentId!=null){
            Query query = Query.query(Criteria.where("refId").is(equipmentId)
                    .and("type").is(ApBehaviorEntry.Type.EQUIPMENT.getCode()));
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            //判断该设备用户是否存在,不存在创建
            if (behaviorEntry==null){
                //不存在,创建
                behaviorEntry = new ApBehaviorEntry();
                behaviorEntry.setCreatedTime(new Date());
                behaviorEntry.setRefId(equipmentId);
                behaviorEntry.setType(ApBehaviorEntry.Type.EQUIPMENT.getCode());
                //存入文档
                mongoTemplate.save(behaviorEntry);
            }
            return behaviorEntry;
        }
        return null;
    }
}
